<?php
namespace App\Models\Traits;

use App\Models\User;
use App\Models\Search;
use Illuminate\Support\Facades\Cache;

trait SearchTrait
{
	protected static function recordSearchToCache($text)
	{
		if (!$user = auth('api')->user()) return;
		
		$cacheKey = $user->searchProductCacheKey();
		$cacheValue = Cache::has($cacheKey) ? Cache::get($cacheKey) : [];
		if (empty($cacheValue)) {
			$cacheValue[] = ['word' => $text];
			Cache::put($cacheKey, $cacheValue, now()->addHours(72));
		} else {
			$hasSameValue = false;
			foreach ($cacheValue as $value) {
				if ($value['word'] == $text) {
					$hasSameValue = true;
					break;
				}
			}
			if (!$hasSameValue) {
				$cacheValue[] = ['word' => $text];
				Cache::put($cacheKey, $cacheValue, now()->addHours(72));
			}
		}
	}
}
